import math
import numpy as np
import matplotlib.pyplot as plt

x = [-3.72, -3.68, -1.35, -0.89, -1.79, -2.85,
     -2.76, -3.72, -3.54, -2.26, -3.45,-3.07,
     -3.99, 2.87, -0.97, 0.79, 1.18, 3.06,
     -1.57, -1.48, -0.74, -0.42, -1.11, 4.25]
y = range(24)
P_w1 = 0.8  # 先验概率1
P_w2 = 0.2  # 先验概率2

mean1 = -1  #均值-1
std1 = np.sqrt(0.16)  #方差0.16
mean2 = 2   #均值2
std2 = np.sqrt(2)  #方差2

data_w1 = []  # 正常细胞
data_w2 = []  # 非正常细胞

x1 = 0
x2 = 0
for x_i in x:
    P_x_w1 = 1 / (std1 * pow(2 * math.pi, 0.5)) * np.exp(-((x_i - mean1) ** 2) / (2 * std1 ** 2))  # 条件概率密度函数1
    P_x_w2 = 1 / (std2 * pow(2 * math.pi, 0.5)) * np.exp(-((x_i - mean2) ** 2) / (2 * std2 ** 2))  # 条件概率密度函数2
    P_x = P_x_w1 * P_w1 + P_x_w2 * P_w2 # x的概率密度函数
    P_w1_x = (P_x_w1 * P_w1) / P_x  # 后验概率1
    P_w2_x = 1 - P_w1_x   # 后验概率2
    P_a1 = 0 * P_w1_x + 4 * P_w2_x
    P_a2 = 4 * P_w1_x + 0 * P_w2_x
    if P_a1 > P_a2:  # 分类正常细胞
        data_w1 = np.append(data_w1, x_i)
        x1 = x1 + 1 # 细胞个数
    if P_a1 < P_a2:  # 分类非正常细胞
        data_w2 = np.append(data_w2, x_i)
        x2 = x2 + 1 # 细胞个数
print("data_w1=", data_w1)
print("data_w2=", data_w2)
print("正常细胞个数:",x1)
print("非正常细胞个数:",x2)
print(P_w1_x)
print(P_w2_x)

plt.rcParams["font.family"] = "SimHei" # 添加了这句话可在图中显示中文
plt.rcParams["axes.unicode_minus"] = False # 添加了这一行使得负号可以显示
plt.scatter(range(x1), data_w1,marker='+',label='正常细胞')
plt.scatter(range(x2), data_w2,marker='o',label='非正常细胞')
plt.title('最小风险贝叶斯决策')
plt.legend()
plt.show()